package cn.rayfoo.common.util.md5;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

/**
 * @author rayfoo@qq.com
 */
public class MD5Utils {


    /**
     * MD5加密
     *
     * @param pwd 需要加密的密码
     * @return
     */
    private static String getMd5Pwd(String pwd) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            // 获取密码
            md.update(pwd.getBytes());
            // 加密
            String newpwd = new BigInteger(1, md.digest()).toString(16);
            return newpwd;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取一个加盐的密码
     *
     * @param pwd 密码
     * @return
     */
    public static String getSaltMd5Pwd(String salt, String pwd) {
        return getMd5Pwd(salt + pwd);
    }

    /**
     * 加盐算法
     *
     * @param n 盐的位数
     * @return
     */
    private static String getSalt(int n) {
        char[] saltTable = ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" +
                "1234567890!@#$%^&*()_+").toCharArray();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < n; i++) {
            //Random().nextInt()返回值为[0,n)
            char aChar = saltTable[new Random().nextInt(saltTable.length)];
            sb.append(aChar);
        }
        return sb.toString();
    }

    /**
     * @param MD5Password md5加密后的密码
     * @param salt 盐
     * @param password 密码
     */
    public static boolean verify(String MD5Password, String salt, String password) {
        if (isNull(MD5Password) || isNull(salt) || isNull(password)) {
            return false;
        }
        return MD5Password.equals(getSaltMd5Pwd(salt, password));
    }

    /**
     * 获取一个32bit的盐
     *
     * @return
     */
    public static String get32BitSalt() {
        return getSalt(32);
    }

    /**
     * 是否为空
     *
     * @param str 参数是否为空
     */
    private static boolean isNull(String str) {
        return str == null || "".equals(str);
    }

    private MD5Utils() {
    }
}
